<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/9/11
 * Time: 上午10:25
 */

namespace app\common\controller;


use app\common\model\CardBonusRule;
use app\common\model\CardCzgive;
use app\common\model\CardMember;
use app\common\model\CardUserBonus;
use app\common\model\CardUserFee;
use app\common\model\Paylog;
use app\common\model\CardUserGet;
use think\Controller;
use think\Request;
use Wechat\Wxobjopen;

class Fztest extends Controller
{
    /*
     * cate 类型
     * 1.充值
     * 2.消费
     * 3.充值赠送
     * 4.消费赠送
     * 5.激活赠送
     * 6.等级赠送
     * 7.分享赠送
     * 8.同步数据
     * 9.积分兑换
     * */
    private $card_id;  //会员卡card_id
    private $poly;  //是否计算多倍
    private $c_id;    //会员卡记录ID；
    private $cs_id;    //充送规则ID；
    private $orderid; //订单编号
    private $oid; //订单编号
    private $code;  //会员卡号
    private $num;  //变动数量
    private $type;//变动 1增加 2减少
    private $cate;  //变动类型   1
    private $pay_cate; //支付方式
    private $source;  //来源
    private $remark; //备注
    private $action_user;//操作人
    private $create_time;
    private $mid;
    private $top_mid;
    private $us_id;
    private $openid;
    private $bd_cate; //变动类型 bonus 积分  balance  余额
    private $is_write; //只写记录
    private $is_bonus; //是否同步赠送积分

    public function __construct($option)
    {
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '0-2:' . json_encode($option) . PHP_EOL, FILE_APPEND);
        //传递参数
        $this->is_write = isset($option['is_write']) ? $option['is_write'] : "yes";
        $this->is_write = isset($option['is_bonus']) ? $option['is_bonus'] : "yes";
        $this->poly = isset($option['poly']) ? $option['poly'] : "";
        $this->cs_id = isset($option['cs_id']) ? $option['cs_id'] : "";
        $this->card_id = $option['card_id'];
        $this->bd_cate = $option['bd_cate'];
        $this->orderid = $option['orderid'];
        $this->code = $option['code'];
        $this->num = $option['num'];
        $this->type = $option['type'];//变动 1增加 2减少
        $this->cate = $option['cate'];  //变动类型
        $this->pay_cate = $option['pay_cate']; //支付方式
        $this->source = $option['source'];  //来源
        $this->remark = $option['remark']; //备注
        $this->action_user = $option['action_user'];//操作人
        $this->create_time = time();
        $CardMember = new CardMember();
        $cardinfo = $CardMember->where('card_id', $option['card_id'])->field('id,card_id')->find();
        $map['card_id'] = $this->card_id;
        $map['code'] = $this->code;
        $CardUserGet = new CardUserGet();
        $userinfo = $CardUserGet->where($map)->field('id,mid,top_mid,card_id,openid,code')->find();
        //基础参数
        $this->mid = $userinfo['mid'];
        $this->top_mid = $userinfo['top_mid'];
        $this->c_id = $cardinfo['id'];
        $this->us_id = $userinfo['id'];
        $this->openid = $userinfo['openid'];


    }

    public function init()
    {
        $orderid = $this->orderid;
        if ($this->type == 1) {
            if (!empty($orderid)) {
                $Paylog = new Paylog();
                $this->oid = $Paylog->where('orderid', $orderid)->value('id');
                //判断是否有充送规则
                if (!empty($this->cs_id)) {
                    $CardCzgive = new CardCzgive();
                    $czinfo = $CardCzgive->where('id', $this->cs_id)->field('bonus,cz_money,zs_money')->find();
                    //判断充送规则是否存在
                    if ($czinfo) {
                        $this->bonus($czinfo['bonus'], 3, 1, "充值赠送", 2);
                        $this->balance($czinfo['cz_money'], 1, 1, "充值", 1, 0);
                        $this->balance($czinfo['zs_money'], 3, 1, "充值赠送", 2, 1, $czinfo['cz_money'], $czinfo['zs_money']);
                    } else {
                        $this->balance("", 1, 1, "充值", 1);
                    }
                } else {
                    if ($this->bd_cate == "bonus") {
                        $this->bonus();
                    } elseif ($this->bd_cate == "balance") {
                        $this->balance();
                        //判断是否同步赠送积分
                        if ($this->is_bonus == "yes") {
                            //判断是否开启积分及多倍积分
                            if (!empty($this->poly)) {
                                $num = $this->getbonuscate();
                            } else {
                                $num = $this->num;
                            }
                            $this->bonus($num, 3, 1, "", $act_source = 2);
                        }
                    }
                }
            } else {
                //判断变动类型
                if ($this->bd_cate == "bonus") {
                    $this->bonus();
                } elseif ($this->bd_cate == "balance") {
                    $this->balance();
                    //判断是否同步赠送积分
                    if ($this->is_bonus == "yes") {
                        //判断是否开启积分及多倍积分
                        if (!empty($this->poly)) {
                            $num = $this->getbonuscate();
                        } else {
                            $num = $this->num;
                        }
                        $this->bonus($num, 3, 1, "", $act_source = 2);
                    }
                }
            }
        } elseif ($this->type == 2) {
            if (!empty($orderid)) {
                $Paylog = new Paylog();
                $this->oid = $Paylog->where('orderid', $orderid)->value('id');
            }
            //判断变动类型
            if ($this->bd_cate == "bonus") {
                $this->bonus();
            } elseif ($this->bd_cate == "balance") {
                $this->balance();
                if ($this->pay_cate !== 4 && $this->pay_cate !== 8) {
                    if (!empty($this->poly)) {
                        $num = $this->getbonuscate();
                    }
                    $this->bonus($num, 4, 1, "消费赠送", $act_source = 2);
                }
            }
        }

    }

    public function getbonuscate($num = "")
    {
        if (!empty($num)) {
            $nums = $num;
        } else {
            $nums = $this->num;
        }
        $CardMember = new CardMember();
        $map['card_id'] = $this->card_id;
        $cardinfo = $CardMember->where($map)->field('bonus_rule,supply_bonus')->find();
        //是否开启积分
        if ($cardinfo['supply_bonus'] == 1) {
            $bonus_rule = json_decode($cardinfo['bonus_rule'], true);
            //比例和积分
            $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
            $add_bonus = floor($nums * $bili);
        } else {
            $add_bonus = $nums;
        }

        $rule = $this->bonusgive();
        $bonus = $rule * $add_bonus;
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '3:' . json_encode($bonus) . PHP_EOL, FILE_APPEND);
        return $bonus;
    }


    public function bonusgive()
    {

        $CardBonusRule = new CardBonusRule();
        //禁止规则
        $map['end_time'] = ['egt', time()];
        $map['card_id'] = $this->card_id;
        $map['statu'] = 0;
        $rule = $CardBonusRule->where($map)->find();
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '0:' . json_encode($rule) . PHP_EOL, FILE_APPEND);
        if ($rule) {
            if ($rule['type'] == 1) {
                $bili = 0;
            } else {
                $bili = $rule['bonus_max'];
            }
        } else {
            //普通
            $bili = 1;
        }
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '1:' . json_encode($bili) . PHP_EOL, FILE_APPEND);
        return $bili;
    }

    public function bonus($num = "", $cate = "", $type = "", $remark = "", $act_source = "")
    {
        $nums = !empty($num) ? $num : $this->num;
        $arr['mid'] = $this->mid;
        $arr['top_mid'] = $this->top_mid;
        $arr['card_id'] = $this->card_id;
        $arr['c_id'] = $this->c_id;
        $arr['orderid'] = $this->orderid;
        $arr['oid'] = $this->oid;
        $arr['us_id'] = $this->us_id;
        $arr['openid'] = $this->openid;
        $arr['code'] = $this->code;
        $arr['num'] = $nums;
        $arr['pay_cate'] = $this->pay_cate;
        $arr['mode'] = 0;//数据写入方式兼容
        $arr['type'] = !empty($type) ? $type : $this->type;; //1增加 2减少
        $arr['cate'] = !empty($cate) ? $cate : $this->cate;
        $arr['source'] = $this->source; //来源
        $arr['remark'] = !empty($remark) ? $remark : $this->remark;  //备注
        $arr['action_user'] = $this->action_user;
        $arr['act_source'] = !empty($act_source) ? $act_source : 1;
        $arr['create_time'] = $this->create_time;
        $Bonus = new CardUserBonus();
        $Bonus->save($arr);
        $this->upddateinfo('bonus', $nums);
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '6:' . json_encode($arr) . PHP_EOL, FILE_APPEND);
        if ($this->is_write == "yes") {
            $this->updatebonus($nums);
        }

    }

    public function balance($num = "", $cate = "", $type = "", $remark = "", $act_source = "", $sendmsg = 1, $cz_money = "", $zs_money = "")
    {
        $nums = !empty($num) ? $num : $this->num;
        $arr['mid'] = $this->mid;
        $arr['top_mid'] = $this->top_mid;
        $arr['card_id'] = $this->card_id;
        $arr['c_id'] = $this->c_id;
        $arr['orderid'] = $this->orderid;
        $arr['oid'] = $this->oid;
        $arr['us_id'] = $this->us_id;
        $arr['openid'] = $this->openid;
        $arr['code'] = $this->code;
        $arr['num'] = $nums;
        $arr['pay_cate'] = $this->pay_cate;
        $arr['mode'] = 0;//数据写入方式兼容
        $arr['type'] = !empty($type) ? $type : $this->type;; //1增加 2减少
        $arr['cate'] = !empty($cate) ? $cate : $this->cate;
        $arr['source'] = $this->source; //来源
        $arr['remark'] = !empty($remark) ? $remark : $this->remark;  //备注
        $arr['action_user'] = $this->action_user;
        $arr['act_source'] = !empty($act_source) ? $act_source : 1;
        $arr['create_time'] = $this->create_time;
        $Balance = new CardUserFee();
        $Balance->save($arr);
        $this->upddateinfo('balance', $nums);
        if ($this->is_write == "yes") {

            if ($sendmsg == 1) {
                if (!empty($zs_money)) {
                    $param['cz_balance'] = $cz_money;
                    $param['zs_balance'] = $zs_money;
                } else {
                    $param['cz_balance'] = $nums;
                    $param['zs_balance'] = 0;
                }
                $this->sendbalancemsg($param);
            }
        }


    }

    /*
     * 更新用户数据库记录 2018-09-11
     *
     * cate  balance 余额  bonus 积分
     * num 变动数量
     * */
    public function upddateinfo($cate, $num)
    {

        $CardUserGet = new CardUserGet();
        if ($this->type == 1) {

            $CardUserGet->where('code', $this->code)->setInc($cate, $num);
        } elseif ($this->type == 2) {
            $CardUserGet->where('code', $this->code)->setDec($cate, $num);
        }
        //更新使用频次
        $CardUserGet->where('code', $this->code)->setInc('frequency', 1);

    }

    /*
     *
     *数据变动 更新微信数据+通知
     *
     */
    public function updatebonus($num)
    {
        //实例化微信
        $WxOption = new Wxoption();
        $options = $WxOption->options($this->card_id);
        $WxObj = new Wxobjopen($options);
        $nums = $this->type == 1 ? $num : -$num;
        $data = [
            'code' => $this->code,
            'card_id' => $this->card_id,
            'record_bonus' => $this->remark,       //说明
//            'bonus' => $this->getuserbonus(),
            'add_bonus' => $nums,             //积分变动值  负数为减少
            'notify_optional' => [
                'is_notify_bonus' => true,
                'is_notify_balance' => false,
                'is_notify_custom_field1' => false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
//        file_put_contents('/data2/html/payos/bonusgive-1.txt', '7:' . json_encode($res) . PHP_EOL, FILE_APPEND);
        if ($res['errcode'] == 0) {
            $Level = new Level();
            $Level->checklevel($this->card_id, $this->code, $res['result_bonus']);
        }

        return $res;
    }

    /*
     *
     *余额变动模板消息通知
     *
     */
    private function sendbalancemsg($param)
    {
        $arr['card_id'] = $this->card_id;
        $arr['type'] = $this->cate;
        $arr['openid'] = $this->openid;
        $arr['add_balance'] = $param['cz_balance'] + $param['zs_balance'];
        $arr['balance'] = $this->getuserfee();

        $TemplateMsg = new TemplateMsg();
        $TemplateMsg->send_tpl('pay_balance', $arr);

    }

    /*
     *
     *获取用户余额
     *
     */
    private function getuserfee()
    {
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where('id', $this->us_id)->value('balance');
        return $user;
    }

    /*
     *
     *获取用户积分
     *
     */
    private function getuserbonus()
    {
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where('id', $this->us_id)->value('bonus');
        return $user;
    }

//    public function updatebalance($num){
//        //实例化微信
//        $WxOption=new Wxoption();
//        $options = $WxOption->options($this->card_id);
//        $WxObj = new Wxobjopen($options);
//        $data = [
//            'code'=>$this->code,
//            'card_id'=>$this->card_id,
//            'custom_field_value2' => $num.'元',
//            'notify_optional'=>[
//                'is_notify_bonus'=>false,
//                'is_notify_balance'=>false,
//                'is_notify_custom_field2'=>false,
//            ],
//        ];
//        $res = $WxObj->updateUserInfo($data);
//        return $res;
//    }

}